package programming.in.scala

/**
  * Created by baiwf on 2017/5/29.
  */
class ch06_Rational(n:Int, d:Int) {
  require(d != 0)
  private val g = gcd(n.abs, d.abs)
  val numer = n/g
  val denom = d/g

  def this(n:Int) = this(n,1)
  def +(that: ch06_Rational):ch06_Rational = {

    new ch06_Rational(numer*that.denom + that.numer * denom,
      denom * that.denom)

    //new ch06_Rational(n * that.d + d*that.n,d*that.d) //编译报错
    // d is not a member of Rational
  }

  def +(i:Int):ch06_Rational = {
    new ch06_Rational(numer + i*denom,denom)
  }

  private def gcd(a:Int, b:Int): Int = {
    if (b == 0) a
    else gcd(b,a%b)
  }

  override def toString: String =  n + "/" + d
  implicit def intToRational(x :Int) = new ch06_Rational(x) //隐式从int转为Rational
}

object ch06Test extends App{
  val v1 = new ch06_Rational(1,2)
  val v2 = new ch06_Rational(1,3)
  println(v1 + v2)
}